package com.zzyy.study.controller;

import com.zzyy.study.annotations.NoLogAnnotation;
import com.zzyy.study.entities.User;
import com.zzyy.study.exp.BusinessException;
import com.zzyy.study.resp.ResultData;
import com.zzyy.study.resp.ReturnCodeEnum;
import com.zzyy.study.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-02-17 16:16
 */
@RestController
public class UserController
{
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    /**
     * 接口方法：com.zzyy.study.controller.UserController.addUser
     * 方法参数列表：{"user":{"username":"张三traceId","password":"13911113333"}}
     * 方法返回值：{"code":"200","message":"success","data":1,"timestamp":1713667631342,"traceId":"1d4789bc35d348919bfd46b5b3c17b76"}
     * 请求地址:http://localhost:24421/user/add,耗时(毫秒):599
     * @param user
     * @return
     */
    @GetMapping(value = "/user/add")
    //@PostMapping(value = "/user/add")
    public ResultData<Integer> addUser(@RequestBody User user)
    {
        log.info("开始执行业务");
        int retValue = userService.addUser(user);
        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        log.info("业务执行结束");
        return ResultData.success(retValue);
    }

    /**
     * 同上一个，但是敏感信息password由于添加了自定义注解@NoLogAnnotation，被干掉了
     * 方法参数列表：{"username":"李四V2traceId"}
     * @param username
     * @param password
     * @return
     */
    @GetMapping(value = "/user/addv2")
    public ResultData<Integer> addUserV2(@RequestParam("username") String username, @NoLogAnnotation @RequestParam("password") String password)
    {
        int retValue = userService.addUser(new User(username,password));
        return ResultData.success(retValue);
    }

    /**
     * 报告异常信息，根据traceId速度定位到哪一行出的bug
     * @param id
     * @return
     */
    @GetMapping(value = "/user/get/{id}")
    public ResultData<User> getUserById(@PathVariable("id") Integer id)
    {
        //这里模拟了一个错误，10/0，会报错
        if(id < 1)
        {
            throw new BusinessException(ReturnCodeEnum.REQPARAM_NEGATIVE.getCode(),ReturnCodeEnum.REQPARAM_NEGATIVE.getMessage());
        }
        return ResultData.success(userService.getUserById(id));
    }

    /**
     *     @NoLogAnnotation添加到了方法上，没有返回值
     * @param userId
     * @param request
     * @return
     */
    @GetMapping("/getUserPassword")
    @NoLogAnnotation
    public ResultData<String> getUserPassword(@RequestParam("userId") String userId, HttpServletRequest request) {
        return ResultData.success("123456");
    }
}
